﻿using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using DG.Tweening;
using IQIGame.Onigao.Framework;
using UnityEngine.Device;

namespace IQIGame.Onigao.GamePlay
{
    public static class DoTweenUtil
    {
        public static async UniTask PlayAsync(this Tween tween, CancellationToken cancel = default)
        {
#if UNITY_EDITOR
            if(!Application.isPlaying)
            {
                StartPreview(tween);
            }
#endif
            {
                // awaitforComplete在重复触发时会丢失
                await tween.SetAutoKill(true).ToUniTask(TweenCancelBehaviour.Kill, cancel);
            }
#if UNITY_EDITOR
            if(!Application.isPlaying)
            {
                StopPreview();
            }
#endif
        }

#if UNITY_EDITOR
        // 加个计数，防止预览中的dotween被提前停止
        private static int _doTweenCount = 0;
        
        public static void StartPreview(this Tween tween)
        {
            _doTweenCount++;
            DG.DOTweenEditor.DOTweenEditorPreview.PrepareTweenForPreview(tween);
            DG.DOTweenEditor.DOTweenEditorPreview.Start();
        }

        public static void StopPreview()
        {
            _doTweenCount = Math.Max(0, _doTweenCount - 1);
            if (_doTweenCount == 0)
            {
                DG.DOTweenEditor.DOTweenEditorPreview.Stop(true);
            }
        }
        
#endif
    }
}